import {
	Button,
	Form,
	Row,
	Col,
	Input,
	message,
	DatePicker,
	Collapse,
	Table,
	Tag,
} from 'antd'
import React, { useState, useEffect, useRef } from 'react'
import { history, connect } from 'umi'
import moment from 'moment'
import type { ColumnsType } from 'antd/es/table'
import styles from './index.less'
import Modal from '@/components/Modal'
import AddPlan from './components/AddPlan'
import PlanDetails from './components/PlanDetails'
import TaskFollowUp from './components/TaskFollowUp'
import {
	addStocktake,
	editStocktake,
	inventoryPlanAuditFlow,
	stocktakeInfo,
	stocktakeInfos,
} from '@/service/storage/assetInventoryPlan'
import Examine from '@/components/Examine'
import { generateStatusType } from '../../../inventoryPlan/dict'
import { processRecordSave } from '@/service/common'

interface DataType {
	id: string
	name: string
	createUser: string
	createTime: string
}

const { TextArea } = Input
const { Panel } = Collapse

const customizeHeader = (value: string) => (
	<div>
		<div className={styles.tip} />
		{value}
	</div>
)

const add = (props: any) => {
	const { query } = props.location
	const [form] = Form.useForm()
	const examineRef = useRef<any>(null)
	const addRef = useRef<any>(null)
	const editRef = useRef<any>(null)
	const [type, setType] = useState<string>()
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [formData, setFormData] = useState<any>({})
	const [detailsData, setDetailsData] = useState<any>()
	const [saveType, setSaveType] = useState(false)
	const [btnLoading, setBtnLoading] = useState(false)
	const [isExamineModalOpen, setIsExamineModalOpen] = useState(false)
	const [examineType, setExamineType] = useState<string>('')
	// 流程id
	const [instanceId, setInstanceId] = useState<string>()
	const [startDate, setStartDate] = useState<any>()
	const [endDate, setEndDate] = useState<any>()
	const [generated, setGenerated] = useState<any>()
	const [dataSource, setDataSource] = useState<any[]>([])

	// 根据路由判断当前页面状态
	useEffect(() => {
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('add')) {
			setType('add')
			form.setFieldsValue({
				planId: '自动生成',
				createUser: '默认为当前账户',
				createTime: '默认为当前时间',
			})
		} else if (hrefs.includes('taskFollowUp')) {
			setType('taskFollowUp')
		} else if (hrefs.includes('edit')) {
			setType('edit')
		} else {
			setType('process')
		}
	}, [])

	useEffect(() => {
		if (query?.planId) {
			stocktakeInfo({ planId: query?.planId }).then((res: any) => {
				if (res?.success) {
					setDetailsData(res?.data)
					setInstanceId(res?.data?.auditProcessId)
					setStartDate(moment(res?.data?.beginTime))
					setEndDate(moment(res?.data?.endTime))
					form.setFieldsValue({
						...res?.data,
						beginTime: moment(res?.data?.beginTime),
						endTime: moment(res?.data?.endTime),
					})
				}
			})
		}
	}, [query])

	useEffect(() => {
		if (
			(type === 'edit' || type === 'view' || type === 'process') &&
			detailsData?.stocktakeId
		)
			stocktakeInfos({
				id: detailsData?.stocktakeId,
			}).then((res: any) => {
				if (res?.success) {
					setGenerated(moment(res?.data?.generateTime))
					setDataSource([res?.data])
				}
			})
	}, [type, detailsData])

	const columns: ColumnsType<DataType> = [
		{
			title: '盘点表名称',
			dataIndex: 'name',
			align: 'center',
			width: 150,
		},
		{
			title: '盘点类型',
			dataIndex: 'type',
			align: 'center',
			width: 150,
			render: (text) => <>{text === 1 ? '全盘' : '抽盘'}</>,
		},
		{
			title: '表单备注',
			dataIndex: 'remark',
			align: 'center',
			width: 250,
		},
		{
			title: '盘点清单生成状态',
			dataIndex: 'generateStatus',
			align: 'center',
			width: 140,
			render: (text: number) => (
				<>
					{generateStatusType?.map(
						(item: { key: number; label: string }) => {
							if (item?.key === text) {
								return (
									<Tag color="processing" key={item?.key}>
										{item?.label}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '创建人',
			width: 100,
			dataIndex: 'createUserName',
			align: 'center',
		},
		{
			title: '创建时间',
			width: 180,
			dataIndex: 'createTime',
			align: 'center',
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 260,
			render: (text: any, record) => (
				<Button
					type="link"
					onClick={() => {
						history.push({
							pathname:
								'/storage/assetInventory/inventoryPlan/view',
							query: {
								id: record?.id,
							},
						})
					}}>
					查看详情
				</Button>
			),
		},
	]

	const onSave = async (types: string) => {
		const value = await form.validateFields()
		const addData = await addRef?.current?.getData()
		const editData = await editRef?.current?.getData()
		if (value) {
			if (type === 'add') {
				setFormData({
					...value,
					...addData,
					beginTime: moment(value?.beginTime).format(
						'YYYY-MM-DD 00:00:00',
					),
					endTime: moment(value?.endTime).format(
						'YYYY-MM-DD 23:59:59',
					),
					isStartAudit: types === 'submit' ? 1 : 0,
				})
				setIsModalOpen(true)
			} else {
				if (
					moment(generated).diff(moment(value?.beginTime), 'days') <=
					0
				) {
					if (
						moment(generated).diff(
							moment(value?.endTime),
							'days',
						) <= 0
					) {
						setIsModalOpen(true)
					} else {
						message.warning(
							'计划结束时间需要大于等于盘点已生成时间',
						)
					}
				} else {
					message.warning('计划开始时间需要大于等于盘点已生成时间')
				}
				setFormData({
					...value,
					...editData,
					beginTime: moment(value?.beginTime).format(
						'YYYY-MM-DD 00:00:00',
					),
					endTime: moment(value?.endTime).format(
						'YYYY-MM-DD 23:59:59',
					),
					isStartAudit: types === 'submit' ? 1 : 0,
				})
			}
		}
	}

	const onSubmit = () => {
		let request: any
		setBtnLoading(true)
		if (query?.planId) {
			// 编辑
			request = editStocktake({ ...formData, id: query.planId })
		} else {
			request = addStocktake(formData)
		}
		request
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
				setBtnLoading(false)
			})
			.catch((err: any) => {
				message.error(err)
				setBtnLoading(false)
			})
	}
	const onExamineType = (types: string) => {
		if (types === '同意') {
			return '1'
		}
		if (types === '驳回') {
			return '2'
		}
		return '3'
	}
	/** 审核 */
	const onCompleteTask = async () => {
		const examineData = await examineRef.current.getData()
		if (examineData) {
			const { url } = examineData || {}
			const flowParams = {
				message: examineData?.message,
				businessId: query?.planId,
				instanceId,
				pass: onExamineType(examineType),
				attachmentList: url?.split(','),
			}
			if (examineType === '拒绝') {
				flowParams.message = JSON.stringify(examineData)
			}
			inventoryPlanAuditFlow(flowParams)
				.then((res: { msg: string; success: boolean }) => {
					if (res?.success) {
						if (examineType === '拒绝') {
							processRecordSave({
								bizType: 15,
								bizNo: query?.planId,
								processId: instanceId,
							})
						}
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}
	}

	return (
		<div className={styles.assetInventoryPlanAdd}>
			<div className={styles.content}>
				{instanceId && (type === 'view' || type === 'process') ? (
					<div className={styles.process}>
						<Examine
							ref={examineRef}
							examineType={type === 'process'}
							orgId={props?.user?.orgId}
							processInstanceId={instanceId}
							bizType={15}
							bizNo={query?.planId}
						/>
					</div>
				) : (
						''
					)}
				<Collapse
					defaultActiveKey={['1', '2', '3', '4', '5']}
					ghost
					expandIconPosition="end"
					collapsible="header"
					className={styles.collapseWrap}>
					<Panel
						header={customizeHeader('基础信息')}
						key="1"
						forceRender>
						<Form
							form={form}
							name="basic"
							layout="horizontal"
							labelCol={{ flex: '140px' }}
							labelAlign="right"
							labelWrap
							autoComplete="off"
							disabled={
								type === 'view' ||
								type === 'taskFollowUp' ||
								type === 'process'
							}>
							<Row gutter={12}>
								<Col
									sm={{ span: 24 }}
									md={{ span: 12 }}
									lg={{ span: 8 }}>
									<Form.Item
										label="盘点计划编号"
										name="planId"
										rules={[{ required: true }]}>
										<Input placeholder="请输入" disabled />
									</Form.Item>
								</Col>
								<Col
									sm={{ span: 24 }}
									md={{ span: 12 }}
									lg={{ span: 8 }}>
									<Form.Item
										label="盘点计划名称"
										name="name"
										rules={[{ required: true }]}>
										<Input placeholder="请输入" />
									</Form.Item>
								</Col>
								<Col
									sm={{ span: 24 }}
									md={{ span: 12 }}
									lg={{ span: 8 }}>
									<Form.Item
										label="盘点负责人"
										name="chargePerson"
										rules={[{ required: true }]}>
										<Input placeholder="请输入" />
									</Form.Item>
								</Col>
								<Col
									sm={{ span: 24 }}
									md={{ span: 12 }}
									lg={{ span: 8 }}>
									<Form.Item
										label="计划开始时间"
										name="beginTime"
										rules={[{ required: true }]}
										tooltip="盘点计划开始时间不能早于要使用的盘点表生成的时间">
										<DatePicker
											allowClear={false}
											onChange={(date) => {
												setStartDate(date)
											}}
											disabledDate={(current) =>
												current && current > endDate
											}
											placeholder="请选择"
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{ span: 24 }}
									md={{ span: 12 }}
									lg={{ span: 8 }}>
									<Form.Item
										label="计划结束时间"
										name="endTime"
										rules={[{ required: true }]}>
										<DatePicker
											allowClear={false}
											onChange={(date) => {
												setEndDate(date)
											}}
											disabledDate={(current) =>
												current && current < startDate
											}
											placeholder="请选择"
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{ span: 24 }}
									md={{ span: 12 }}
									lg={{ span: 8 }}
								/>

								{type !== 'add' ? (
									<>
										<Col
											sm={{ span: 24 }}
											md={{ span: 12 }}
											lg={{ span: 8 }}>
											<Form.Item
												label="创建人"
												name="createUser">
												<Input
													disabled
													placeholder="请输入"
												/>
											</Form.Item>
										</Col>
										<Col
											sm={{ span: 24 }}
											md={{ span: 12 }}
											lg={{ span: 8 }}
											style={{ marginRight: '10px' }}>
											<Form.Item
												label="创建时间"
												name="createTime">
												<Input
													disabled
													placeholder="请选择"
												/>
											</Form.Item>
										</Col>
									</>
								) : (
										''
									)}
								<Col span={16}>
									<Form.Item
										label="盘点要求描述"
										name="description"
										rules={[{ required: true }]}>
										<TextArea
											maxLength={200}
											placeholder="请输入（最多100个字）"
											autoSize={{ minRows: 3, maxRows: 6 }}
										/>
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</Panel>
					{type === 'edit' ||
						type === 'view' ||
						type === 'process' ? (
							<Panel
								header={customizeHeader('盘点表')}
								key="5"
								forceRender>
								<Table
									columns={columns}
									dataSource={dataSource}
									pagination={false}
									loading={false}
									bordered
								/>
							</Panel>
						) : (
							''
						)}

					{type === 'add' ? (
						<AddPlan
							ref={addRef}
							dataSource={{}}
							startDate={startDate}
						/>
					) : (
							''
						)}
					{type === 'taskFollowUp' ? (
						<TaskFollowUp planId={query?.planId} />
					) : (
							''
						)}
				</Collapse>
				{type === 'view' || type === 'edit' || type === 'process' ? (
					<PlanDetails
						ref={editRef}
						data={detailsData}
						type={type}
						id={query?.planId}
					/>
				) : (
						''
					)}

				<div className={styles.wrap}>
					{type === 'process' ? (
						<>
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => {
									setExamineType('同意')
									setIsExamineModalOpen(true)
								}}>
								同意
							</Button>
							<Button
								onClick={() => {
									setExamineType('驳回')
									setIsExamineModalOpen(true)
								}}>
								驳回
							</Button>
							<Button
								onClick={() => {
									setExamineType('拒绝')
									setIsExamineModalOpen(true)
								}}>
								拒绝
							</Button>
						</>
					) : (
							''
						)}
					{type === 'view' ||
						type === 'process' ||
						type === 'taskFollowUp' ? (
							<Button
								onClick={() => {
									history.go(-1)
								}}>
								返回
							</Button>
						) : (
							<>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => {
										onSave('save')
										setSaveType(true)
									}}>
									保存
							</Button>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => {
										onSave('submit')
										setSaveType(false)
									}}>
									提交
							</Button>
								<Button
									onClick={() => {
										history.go(-1)
									}}>
									取消
							</Button>
							</>
						)}
				</div>
			</div>
			<Modal
				text={
					saveType
						? `确定要保存吗？请仔细核对所填信息`
						: '确定要提交吗？提交后自动保存并开始审批，请仔细核对所填信息'
				}
				onSubmit={onSubmit}
				loading={btnLoading}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
			<Modal
				text={`确定要${examineType}吗？请仔细核对所填信息`}
				loading={btnLoading}
				onSubmit={onCompleteTask}
				isModalOpen={isExamineModalOpen}
				setIsModalOpen={setIsExamineModalOpen}
			/>
		</div>
	)
}
export default connect(({ user }: any) => ({ user }))(add)
